home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6639 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: ix.netcom.com!netnews
  2. From: miker3@ix.netcom.com (Mike Rubenstein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to tell if a file exists in C
  5. Date: Thu, 15 Feb 1996 03:32:07 GMT
  6. Organization: Netcom
  7. Message-ID: <3122a294.94201494@nntp.ix.netcom.com>
  8. References: <4eqkj6$ipo@charm.magnus.acs.ohio-state.edu> <4eqn9q$dr1@sparcserver.lrz-muenchen.de> <3121db3e.43150046@nntp.ix.netcom.com> <4ftpnk$i74@cafu.fl.net.au>
  9. NNTP-Posting-Host: ix-dc14-24.ix.netcom.com
  10. X-NETCOM-Date: Wed Feb 14  7:32:06 PM PST 1996
  11. X-Newsreader: Forte Agent .99d/32.182
  12.  
  13. als@fl.net.au (Andrew Snow) wrote:
  14.  
  15. > miker3@ix.netcom.com (Mike Rubenstein) wrote:
  16. > >ua302aa@sun2.lrz-muenchen.de (Kurt Watzka) wrote:
  17. > >> xiaoyi@bmecg.bme.ohio-state.edu (Xiaoyi Wu) writes:
  18. > >> 
  19. > >> >Hi, how do I find out if a file already exists
  20. > >> >in UNIX C? On PCs I would do a findfirst/findnext,
  21. > >> >is there an equivalent on Unix?
  22. > >> 
  23. > >> Yes, there is an equivalent in a POSIX environment, but there 
  24. > >> is a portable solution in C, too. The fopen()-function can 
  25. > >> be used to decide whether a file is accessible for reading,
  26. > >> and if it is not accessible for reading, errno can be used
  27. > >> to detect the reason for that.
  28. > >Unfortunately, this is not portable.  Nothing in the C standard
  29. > >requires fopen() to set errno to a sensible value (or, for that
  30. > >matter, to set it at all) if there is an error.
  31. > How about plain old:
  32. >     if(0==access("filename", F_OK))
  33. >         {
  34. >         do stuff with file();
  35. >         }
  36. >     else
  37. >         {
  38. >         error();
  39. >         }
  40. > This works O.K. under Linux and FreeBSD, and most DOS compilers.
  41. > If you want to see if the file is readable as well as exists,
  42. > use     if(0==access("filename", F_OK | R_OK))
  43. >         ...
  44. > or writeable, use F_OK | R_OK | W_OK
  45. > and so on.
  46.  
  47. In many cases that would be my preference.  In others, where true
  48. portability is important, I'd go with using fopen(), but without
  49. checking errno to determine the cause if it fails.
  50.  
  51. While it's true that access() is defined on many systems, there's more
  52. needed for portability.  Header files that are needed are not
  53. standardized.  Also there are some differences in implementations.
  54. Microsoft (VC++ 4.0) for example calls the function _access and does
  55. not define F_OK, etc.
  56.  
  57.  
  58. Michael M Rubenstein
  59.